package com.hkp.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期格式转换配置类
 */
@Configuration
public class DateConverterConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 添加日期格式转换器
        registry.addConverter(new DateConverter());
    }

    /**
     * 日期转换器
     */
    public static class DateConverter implements Converter<String, Date> {
        private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public Date convert(String source) {
            if (source == null || source.trim().isEmpty()) {
                return null;
            }
            try {
                return sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期格式转换错误，请使用yyyy-MM-dd格式", e);
            }
        }
    }
}